#include "jsonhelper.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDir>
JsonHelper::JsonHelper(QObject *parent) :
    QObject(parent),
    m_filePath("./data/audiodata.data"),
    m_objFile(m_filePath)
{
    this->m_i32CurrentIndex = -1 ;
    // 检查文件是否存在
    if (!this->m_objFile.exists()) {
        qDebug() << "File does not exist:" << this->m_filePath;
        return ;
    }
    if( ! this->m_objFile.open(QIODevice::ReadWrite ) )
    {
        qDebug() << "Open File fail : " << this->m_filePath;
        return;
    }
}

JsonHelper::~JsonHelper()
{
    this->m_objFile.close();
}



void JsonHelper::serializeData( QVariant data )
{
    //移动文件指针
    this->m_objFile.resize(0);
    this->m_objFile.seek(0);
    this->m_objFile.write( data.toString().toUtf8() );
}

void JsonHelper::deserializeData(QVariant key)
{
    //置空
    this->m_objFile.seek(0);
    this->m_objFmData.clear();
     this->m_i32CurrentIndex = -1 ;

    QByteArray jsonData = this->m_objFile.readAll();

    // 将JSON字符串转换为QJsonDocument对象
    QJsonDocument doc = QJsonDocument::fromJson( jsonData );
    // 获取JSON对象
    QJsonObject obj = doc.object();

    if( "fm_ch" == key)
    {
        // 获取fm_ch数组
        QJsonArray fmChArray = obj[key.toString()].toArray();

        for (const QJsonValue &value : fmChArray) {
            QJsonObject fmChObj = value.toObject();
            FmData *fmData = new FmData(this);
            fmData->setFreq( fmChObj["freq"].toInt() );
            fmData->setFav( fmChObj["fav"].toInt() );
            this->m_objFmData.append( QVariant::fromValue( fmData ) );

            //  qDebug() <<"freq : " << fmData.freq  << " fav : " << fmData.fav;
        }
    }
    else if( "index" == key )
    {
        this->m_i32CurrentIndex = obj[key.toString()].toInt();

    }
}


QVariantList JsonHelper::getFmData()
{
    return this->m_objFmData;
}

int JsonHelper::getCurrentIndex()
{
    return this->m_i32CurrentIndex;
}
